package com.lg.teacherCrud.controller;


import com.lg.teacherCrud.entity.Teacher;
import com.lg.teacherCrud.service.TeacherService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.List;

@RestController
@RequestMapping("/teachers")
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    // 添加教师
    @PostMapping
    public String createTeacher(@RequestParam String name, @RequestParam String course, @RequestParam Date birthday) {
        Teacher teacher = new Teacher();
        teacher.setName(name);
        teacher.setCourse(course);
        teacher.setBirthday(birthday);
        teacherService.save(teacher);  // 使用MyBatis-Plus的save方法
        return "添加教师成功";
    }

    // 获取特定教师信息
    @GetMapping("/{id}")
    public Teacher getTeacherById(@PathVariable int id) {
        return teacherService.getById(id);  // 使用MyBatis-Plus的getById方法
    }

    // 获取所有教师信息
    @GetMapping
    public List<Teacher> getAllTeachers() {
        return teacherService.list();  // 使用MyBatis-Plus的list方法
    }

    // 更新教师信息
    @PutMapping("/{id}")
    public String updateTeacher(@PathVariable int id, @RequestParam String name, @RequestParam String course, @RequestParam Date birthday) {
        Teacher teacher = teacherService.getById(id);
        if (teacher != null) {
            teacher.setName(name);
            teacher.setCourse(course);
            teacher.setBirthday(birthday);
            teacherService.updateById(teacher);  // 使用MyBatis-Plus的updateById方法
            return "更新教师成功";
        } else {
            return "教师不存在";
        }
    }

    // 删除单个教师
    @DeleteMapping("/{id}")
    public String deleteTeacherById(@PathVariable int id) {
        teacherService.removeById(id);  // 使用MyBatis-Plus的removeById方法
        return "删除教师成功";
    }

    // 删除所有教师
    @DeleteMapping
    public String deleteAllTeachers() {
        teacherService.remove(null);  // 使用MyBatis-Plus的remove方法删除所有记录
        return "删除所有教师成功";
    }

    // 批量插入教师
    @PostMapping("/batchInsert")
    public String batchInsertTeachers() {
        teacherService.batchInsertTeachers();
        return "批量插入完成";
    }

    // 获取倒数第二条记录
    @GetMapping("/secondLast")
    public Teacher getSecondLastTeacher() {
        return teacherService.getSecondLastTeacher();
    }
}